var express = require("express");
var { newLoginModel } = require("../db/index");
var router = express.Router();
var multiparty = require("multiparty");
const SMSClient = require("@alicloud/sms-sdk");
const svgCaptcha = require("svg-captcha");
const jwt = require("jsonwebtoken");

// 赵航代码块

// 短信验证码

const accessKeyId = "";
const secretAccessKey = "";
const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
var yzm = null;

// 发送短信验证码的接口
router.post("/send-sms", async (req, res) => {
  const { phoneNumber } = req.body;
  console.log(phoneNumber);
  if (!phoneNumber) {
    return res.status(400).json({ success: false, message: "手机号不能为空" });
  }

  // 生成随机验证码
  const code = Math.floor(100000 + Math.random() * 900000).toString();
  try {
    // 调用阿里云短信服务
    const result = await smsClient.sendSMS({
      PhoneNumbers: phoneNumber, // 目标手机号
      SignName: "yzm实现", // 短信签名（需与阿里云控制台一致）
      TemplateCode: "SMS_479960123", // 短信模板CODE（需与阿里云控制台一致）
      TemplateParam: `{"code":"${code}"}`, // 短信模板中的变量
    });

    console.log("阿里云返回结果:", JSON.stringify(result, null, 2)); // 打印阿里云返回的结果

    if (result.Code === "OK") {
      // 验证码发送成功
      console.log(`验证码已发送至 ${phoneNumber}，验证码为：${code}`);
      yzm = code;
      res.json({ success: true, message: "验证码发送成功" });
    } else {
      // 发送失败
      console.error("短信发送失败:", result.Message);
      res.status(500).json({
        success: false,
        message: "短信发送失败",
        error: result.Message,
      });
    }
  } catch (error) {
    console.error("短信服务异常:", error.message);
    res
      .status(500)
      .json({ success: false, message: "短信服务异常", error: error.message });
  }
});

router.post("/sjdl", async function (req, res) {
  let { aa } = req.body;
  console.log(aa);
  console.log(yzm);
  if (aa == yzm) {
    res.send({ success: true, message: "验证码正确" });
  } else {
    res.send({ success: false, message: "验证码错误" });
  }
});

//图形验证码

router.get("/captcha", (req, res) => {
  const captcha = svgCaptcha.createMathExpr({
    size: 5, // 验证码长度
    noise: 3, // 干扰线条数量
    height: 56,
    width: 110, // 验证码宽度
    color: true, // 验证码字符有颜色
    background: "#c3a6ef", // 背景颜色
  });

  // 返回验证码图片和文本
  res.type("svg");
  res.send({
    data: captcha.data, //SVG图片数据
    text: captcha.text, // 验证码文本
  });
});

// 验证返回的验证码
router.post("/verify-captcha", (req, res) => {
  const { inp, captcha } = req.body;
  if (inp == captcha) {
    res.send({
      inp,
    });
  } else {
    res.send({
      code: 400,
    });
  }
});

// 添加用户
router.post("/zadd", (req, res) => {
  newLoginModel.create(req.body).then((data) => {
    res.send({
      code: 200,
      message: "添加成功",
    });
  });
});

// 用户登录
router.post("/zlogin", (req, res) => {
  console.log(req.body);
  newLoginModel
    .findOne({ email: req.body.email, password: req.body.password })
    .then((data) => {
      if (data) {
        let token = jwt.sign({ email: req.body.email }, "123456789", {
          expiresIn: "1h",
        });
        res.send({
          code: 200,
          data,
          token,
        });
      } else {
        res.send({
          code: 400,
          data,
        });
      }
    });
});

// 手机登录
router.post("/zsjlogin", (req, res) => {
  console.log(req.body);
  newLoginModel.findOne({ phone: req.body.phone }).then((data) => {
    if (data) {
      res.send({
        code: 200,
        data,
      });
    } else {
      res.send({
        code: 400,
        data,
      });
    }
  });
});

// 上传图片
router.post("/upload", (req, res) => {
  // 创建multiparty对象
  let form = new multiparty.Form();
  // 配置上传目标位置
  form.uploadDir = "upload";
  //配置上传的文件
  form.parse(req, (err, a, b) => {
    console.log(a, b);
    res.send({
      path: b.file[0].path,
    });
  });
});

// token验证
// router.post("/token", async (req, res) => {
//   let { lemail } = req.body;
//   let findUser = await newLoginModel.find({ email: lemail });
//   if (findUser.length != 0) {
//     res.send({
//       code: 200,
//       token,
//     });
//   }
// });

// 张芯芯代码块
//获取登录姓名
router.get("/name", (req, res) => {
  const obj = req.query;
  console.log(obj, "111111");
  newLoginModel
    .findOne({
      $or: [{ email: obj.email }, { phone: obj.phone }],
    })
    .then((data) => {
      res.send({
        code: 200,
        data,
      });
    });
});
// // 李名扬代码块
// 引入短信服务模块
const smsService = require("./smsService");

// 存储验证码，实际应用中建议使用数据库
const verificationCodes = {};

// 发送验证码接口
router.post("/send-verification-code", async (req, res) => {
  const { phoneNumber } = req.body;
  if (!phoneNumber) {
    return res.status(400).json({ success: false, message: "请提供手机号码" });
  }
  try {
    // 生成验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    // 存储验证码
    verificationCodes[phoneNumber] = code;
    // 发送短信验证码
    const result = await smsService.sendVerificationCode(phoneNumber, code);
    if (result.Code === "OK") {
      res.status(200).json({ success: true, message: "验证码发送成功" });
    } else {
      res.status(500).json({ success: false, message: "验证码发送失败" });
    }
  } catch (error) {
    console.error("发送短信出错:", error.message);
    res.status(500).json({ success: false, message: "验证码发送失败" });
  }
});

// 验证验证码接口
router.post("/verify-code", (req, res) => {
  const { phoneNumber, code } = req.body;
  console.log(req.body);
  if (!phoneNumber || !code) {
    return res
      .status(400)
      .json({ success: false, message: "请提供手机号码和验证码" });
  }
  const storedCode = verificationCodes[phoneNumber];
  console.log(storedCode, typeof storedCode);

  if (storedCode == code) {
    // 验证成功后删除验证码
    delete verificationCodes[phoneNumber];
    res.status(200).json({ success: true, message: "验证码验证成功" });
  } else {
    res.status(400).json({ success: false, message: "验证码验证失败" });
  }
});

//渲染
router.get("/lLogin", (req, res) => {
  const obj = req.query;
  console.log(obj);

  newLoginModel
    .findOne({
      $or: [{ email: obj.lemail }, { phone: obj.lphone }],
    })
    .then((data) => {
      res.send({
        code: 200,
        data,
      });
    });
});
//修改信息
router.put("/lput", (req, res) => {
  const obj = req.body;
  console.log(obj);

  newLoginModel.updateOne({ _id: obj._id }, obj).then((data) => {
    res.send({
      code: 200,
      message: "修改成功",
    });
  });
});

//修改密码
router.put("/lput", (req, res) => {
  const obj = req.body;
  console.log(obj);

  newLoginModel
    .updateOne({ _id: obj._id }, { password: obj.password })
    .then((data) => {
      res.send({
        code: 200,
        message: "修改成功",
      });
    });
});
// 消息
const WebSocket = require("ws");
// 创建 WebSocket 服务器
const server = new WebSocket.Server({ port: 8080 });
const clients = new Set();

server.on("connection", (ws) => {
  clients.add(ws);
  console.log("A new client connected");

  ws.on("message", (message) => {
    let receivedMessage;
    console.log(`Received: ${message}`);
    if (Buffer.isBuffer(message)) {
      receivedMessage = message.toString(); // 将 Buffer 转换为字符串
    } else {
      receivedMessage = message; // 如果是字符串，直接使用
    }
    // 将接收到的消息广播给所有连接的客户端
    clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(receivedMessage);
      }
    });
  });

  ws.on("close", () => {
    clients.delete(ws);
    console.log("A client disconnected");
  });
});

console.log("WebSocket server is running on ws://localhost:8080");

// 杨玉涛代码块

// 蔡红岩代码块

// 闫嘉辉代码块

// 陈子尚代码块

module.exports = router;
